package com.siteseat.common.entity;

import java.util.HashMap;
import java.util.Map;

import com.siteseat.common.exception.InternalException;

/**
 *
 */
public class NamedEntityManager<T extends NamedEntity> extends EntityManager<T> {

  private Map<String, T> nameMap = new HashMap<String, T>();
  
  public T findByName(String name) {
    return listByName().get(name);
  }
  
  public Map<String,T> listByName() {
    return nameMap;
  }
  
  public void remove( T u ) {
    Integer id = u.getId();
    Integer pos = positions.get( id );
    if( pos != null ) {
      positions.remove( id );
      entityList.remove( pos );
      idMap.remove( id );
      nameMap.remove( u.getName() );        
    }
  }

  /**
   */
  public void add( T u ) {    
    Integer id = u.getId();
    if( idMap.containsKey(id) ) {
      throw new InternalException( "Duplicated entity id: " + id );
    }
    idMap.put( id, u );
    
    String name = u.getName();
    if( nameMap.containsKey(name) ) {
      throw new InternalException( "Duplicated entity name: " + name );
    }
    nameMap.put( name, u );
    
    entityList.add( u );
    positions.put( id, Integer.valueOf(entityList.size() - 1) );
  }
  
  
}
